//
//  OrderCompleteUpLoadImageViewController.m
//  SsehMaster
//
//  Created by 杨阳 on 2018/11/13.
//  Copyright © 2018 yinlong. All rights reserved.
//

#import "OrderCompleteUpLoadImageViewController.h"
#import "OrderCompleteUpLoadImageTableViewCell.h"
#import "SsehPublicModel.h"
#import "SXPickPhoto.h"
#import "OrderInforModel.h"

@interface OrderCompleteUpLoadImageViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * dataSource;

@property (nonatomic,strong) SXPickPhoto * pickPhoto;

@property (nonatomic,strong) NSString * uploadImageF,*uploadImageB;

@end

static NSString * const OrderCompleteUpLoadImageTableViewCellID = @"OrderCompleteUpLoadImageTableViewCellID";

@implementation OrderCompleteUpLoadImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self baseSetting];
    [self layoutUI];
}

-(void)baseSetting{
    
    self.navigationItem.title = @"上传照片";
    
}

-(void)layoutUI{
    
    CGFloat tHeight = 0.0f;
    if ([self.typ isEqualToString:@"1"]) {
        tHeight = VIEW_HEIGHT-NAVIGATION_BAR_HEIGHT-HOME_INDICATOR_HEIGHT-5-60;
    }else{
        tHeight = VIEW_HEIGHT-NAVIGATION_BAR_HEIGHT-HOME_INDICATOR_HEIGHT-5;
    }
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,5, VIEW_WIDTH, tHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.layer.cornerRadius = 5;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.backgroundColor = [UIColor backGroudColorForView];
    [self.tableView registerNib:[UINib nibWithNibName:@"OrderCompleteUpLoadImageTableViewCell" bundle:nil] forCellReuseIdentifier:OrderCompleteUpLoadImageTableViewCellID];
    [self.view addSubview:self.tableView];
    
    if ([self.typ isEqualToString:@"1"]){
        //footerView
        __weak typeof (self)weakSelf = self;
        UIView * footerView = [UIView new];
        footerView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:footerView];
        [footerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.height.mas_equalTo(60);
            make.bottom.equalTo(weakSelf.view).offset(-HOME_INDICATOR_HEIGHT);
        }];
        
        //维修确认
        UIButton * sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
        sureButton.titleLabel.font = [UIFont systemFontOfSize:14];
        sureButton.layer.cornerRadius = 3.0f;
        sureButton.backgroundColor = [UIColor appColor];
        [sureButton addTarget:self action:@selector(sureButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [sureButton setTitle:@"提交" forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [footerView addSubview:sureButton];
        [sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.mas_equalTo(UIEdgeInsetsMake(10, 30, 10, 30));
            
        }];
    }    
}

-(void)sureButtonClick:(UIButton *)button{
    
    //upLoadAnyImageWithURL
    if (![self imageIsComplent]) {
        [self showTipWithTitle:@"至少需要一张照片"];
        return;
    }
    [self showLoading];
    [self repairF];

}

-(void)repairF{
    [self showLoading];
    SsehPublicModel * model = [self.dataSource firstObject];
    
    [[QYNetManager sharedManager]upLoadAnyImageWithURL:@"https://member.yinweish.com/settingInterfaces/v1.0/uploadImgs" parameters:nil andSsehPublicModel:model SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            
            NSArray * arr = responseObject[@"data"];
            NSMutableString * mStr = [[NSMutableString alloc]initWithCapacity:0];
            for (NSInteger i = 0; i < arr.count; i++) {
                NSString * str = arr[i];
                NSString * imageUrl = [NSString stringWithFormat:@"%@%@",kSsehImageIP,str];
                if (i == arr.count-1) {
                    [mStr appendString:imageUrl];
                }else{
                    [mStr appendFormat:@"%@,",imageUrl];
                }
            }
            self.uploadImageF = mStr;
            [self performSelector:@selector(repairB) withObject:nil afterDelay:1.0f];
        }
        
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(void)repairB{
    
    [self showLoading];
    SsehPublicModel * model = self.dataSource[1];
    
    [[QYNetManager sharedManager]upLoadAnyImageWithURL:@"https://member.yinweish.com/settingInterfaces/v1.0/uploadImgs" parameters:nil andSsehPublicModel:model SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            
            NSArray * arr = responseObject[@"data"];
            NSMutableString * mStr = [[NSMutableString alloc]initWithCapacity:0];
            for (NSInteger i = 0; i < arr.count; i++) {
                NSString * str = arr[i];
                NSString * imageUrl = [NSString stringWithFormat:@"%@%@",kSsehImageIP,str];
                if (i == arr.count-1) {
                    [mStr appendString:imageUrl];
                }else{
                    [mStr appendFormat:@"%@,",imageUrl];
                }
            }
            self.uploadImageB = mStr;
            [self performSelector:@selector(upLoadImageIP) withObject:nil afterDelay:1.0f];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(void)upLoadImageIP{
    
    [self showLoading];
    NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],
                           @"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],
                           @"order_id":[NSString emptyStr:self.orderModel.order_id],
                           @"order_maintail_imgs1":[NSString emptyStr:self.uploadImageF],
                           @"order_maintail_imgs2":[NSString emptyStr:self.uploadImageB]
                           };
    
    [[QYNetManager sharedManager]POST:kUpdateMaintailOrder parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]){
            [self showTipWithTitle:@"上传成功"];
            [self performSelector:@selector(popBack) withObject:nil afterDelay:1.0f];
        }else{
            [self showTipWithTitle:@"上传失败"];
        }
        
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showTipWithTitle:SsehPoolNetStr];
    }];
}

-(void)popBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 250;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OrderCompleteUpLoadImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:OrderCompleteUpLoadImageTableViewCellID];
    
    SsehPublicModel * model = self.dataSource[indexPath.section];
    [cell configData:model andIndex:indexPath];
    __weak typeof (self)weakSelf = self;
    cell.imageViewClick = ^( NSIndexPath * _Nonnull index) {
        [weakSelf aleShowView:index];
    };
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * hView = [[UIView alloc]init];
    hView.backgroundColor = [UIColor whiteColor];
    
    UILabel * titleLabel = [UILabel new];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = RGBColor(102, 102, 102);
    if (section == 0) {
        titleLabel.text = @"未维修";
    }else{
        titleLabel.text = @"已维修";
    }
    [hView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.equalTo(hView);
        make.left.equalTo(hView).offset(15);
        
    }];
    
    UIView * lineView = [UIView new];
    lineView.backgroundColor = [UIColor backGroudColorForView];
    [hView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(hView);
        make.height.mas_equalTo(1);
    }];
    
    return hView;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 5;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = [UIColor backGroudColorForView];
    return view;
}


#pragma mark - 照相

- (void)aleShowView:(NSIndexPath *)index
{
    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    //拍照：
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.pickPhoto ShowTakePhotoWithController:self andWithBlock:^(NSObject *Data) {
            if ([Data isKindOfClass:[UIImage class]])
            {
                NSData * imageData = UIImageJPEGRepresentation((UIImage *)Data, 0.3);
                UIImage * newImage1 = [UIImage imageWithData:imageData];
                SsehPublicModel * model = self.dataSource[index.section];
                NSMutableArray * imageArr = [[NSMutableArray alloc]initWithArray:model.imageArr];
                [imageArr addObject:newImage1];
                model.imageArr = [NSArray arrayWithArray:imageArr];
                [self.tableView reloadData];
            }
        }];
    }];
    //相册
    UIAlertAction * act3 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //打开相册
        [self.pickPhoto SHowLocalPhotoWithController:self andWithBlock:^(NSObject *Data) {
            if ([Data isKindOfClass:[UIImage class]])
            {
                NSData * imageData = UIImageJPEGRepresentation((UIImage *)Data, 0.3);
                UIImage * newImage1 = [UIImage imageWithData:imageData];
                SsehPublicModel * model = self.dataSource[index.section];
                NSMutableArray * imageArr = [[NSMutableArray alloc]initWithArray:model.imageArr];
                [imageArr addObject:newImage1];
                model.imageArr = [NSArray arrayWithArray:imageArr];
                [self.tableView reloadData];
            }
        }];
    }];
    
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:nil message:@"选择上传方式" preferredStyle:UIAlertControllerStyleActionSheet];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    [aleVC addAction:act3];
    
    [self presentViewController:aleVC animated:YES completion:nil];
}

-(BOOL)imageIsComplent{
    
    BOOL imageArr1 = NO;
    BOOL imageArr2 = NO;
    
    for (NSInteger i = 0; i< self.dataSource.count; i++) {
        SsehPublicModel * model = self.dataSource[i];
        if (kArrayIsEmpty(model.imageArr)) {
            switch (i) {
                case 0:
                    imageArr1 = NO;
                    break;
                case 1:
                    imageArr2 = NO;
                    break;
                    
                default:
                    break;
            }
        }else{
            switch (i) {
                case 0:
                    imageArr1 = YES;
                    break;
                case 1:
                    imageArr2 = YES;
                    break;
                    
                default:
                    break;
            }
        }
    }
    if (imageArr1 == YES && imageArr2 == YES) {
        return YES;
    }
    return NO;
}

-(NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc]initWithCapacity:0];
        for (NSInteger i = 0; i < 2; i++) {
            
            SsehPublicModel * model = [[SsehPublicModel alloc]init];
            model.imageArr = [[NSArray alloc]init];
            switch (i) {
                case 0:
                    model.titleStr = @"order_maintail_imgs1";
                    model.infoStr = [NSString emptyStr:self.orderModel.order_maintail_imgs1];
                    model.statyStr = [NSString emptyStr:self.typ];
                    break;
                case 1:
                    model.titleStr = @"order_maintail_imgs2";
                    model.infoStr = [NSString emptyStr:self.orderModel.order_maintail_imgs2];
                    model.statyStr = [NSString emptyStr:self.typ];
                    break;
                    
                default:
                    break;
            }
            [_dataSource addObject:model];
            
        }
    }
    return _dataSource;
}

-(SXPickPhoto*)pickPhoto{
    if (!_pickPhoto) {
        _pickPhoto = [[SXPickPhoto alloc]init];
    }
    return _pickPhoto;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
